<template>
    <t-adaptive-page
        v-loading="state.loading"
        class="menu_mange"
        tableTitle="合同条款类型"
        row-key="path"
        isCopy
        ref="tAdaptivePageRef"
        isExpansion
        :isTTableSelfFilling="false"
        :isShowPagination="false"
        columnSetting
        :table="state.table"
        :columns="state.table.columns"
        isShowWidthSize
        :opts="opts"
        :widthSize="4"
        @submit="conditionEnter"
        @selection-change="selecUpdateChange"
    >
      <template #CreateDate="{scope}">
        <div>{{ parseTime(scope.row.CreateDate) }}</div>
      </template>

      <template #Name="{ scope }">
        <el-input v-model="scope.row.Name" placeholder="请输入内容" clearable></el-input>
      </template>

      <template #footerBtn>
        <el-button type="danger" @click="add" v-if="checkPermission('新增', state.roleList)">新增</el-button>
        <el-button type="danger" @click="addHandle()" v-if="checkPermission('新增', state.roleList)">保存</el-button>
        <el-button type="danger" @click="deleteHandles" :disabled="!state.ids.length" v-if="checkPermission('删除', state.roleList)">删除</el-button>

        <el-button type="primary" @click="tAdaptivePageRef.TQueryConditionPage.checkHandle()">查询</el-button>
        <el-button type="danger" @click="tAdaptivePageRef.TQueryConditionPage.resetHandle()">重置</el-button>
      </template>

      <!--  新增 / 修改-->
      <template #operator="{ scope }">
        <el-button type="primary" link v-if="checkPermission('删除', state.roleList)" @click="deleteHandles(scope.row)">删除</el-button>
      </template>

    </t-adaptive-page>
  </template>

  <script setup lang="tsx">
  import {computed, onMounted, reactive, ref, toRefs, unref, watch} from "vue"
  import {} from "@/api/base"
  import {getTKType,DelTKType,SaveTKType,userRole} from "@/api/base"
  import {parseTime,checkPermission} from "@/utils/util";
  import {cubasdocStore} from "@/stores/modules/cubasdoc";
  import {ElMessage, ElMessageBox} from "element-plus";
  const tAdaptivePageRef: any = ref(null)
  const selectTable = ref()


  const cubasdoc = cubasdocStore()


  import type { UploadProps, UploadUserFile } from 'element-plus'


  const handlEedit = async (row: any)  => {

    let {Data} = await getTKType({Code:'',Name:''})

    state.formData = Data.Main
    state.clumTable.data = Data.SubList


    //过滤合同
    let contractInfo = cubasdoc.contractList.find((item: any) => item.ContractNum == row.ContractNum)
    if (contractInfo){
      await findContractInfo(contractInfo.Id)
      state.defaultSelectVal = Data.SubList.map((item: any) => item.ConSubId)
      //

      state.dialogSelectEnt = true
    }

  }

  const handleDelete = (row: any) => {

    state.clumTable.data.splice(state.clumTable.data.indexOf(row), 1)
  }


  //表格配置
  const state: any = reactive({
    roleList: [],
    queryData: {
      Code: '', // 类型编号
      Name: '', // 类型名称
    },
    table: {
      border: true,
      // 接口返回数据
      data: [],
      firstColumn: { type: "selection", fixed: true },
      // 表头数据
      columns: [
        { prop: "Code", label: "编码", minWidth: 120 },
        { prop: "Name", label: "条款类型名称", minWidth: 200
          ,canEdit: true,
          configEdit: {
            label: "开始编号",
            type: "input",
            editSlotName: "Name",
            editComponent: "el-input"
          }
        },
        { prop: "CreateBy", label: "建档人",minWidth: 120},
        { prop: "CreateDate", label: "建档日期  ",minWidth: 120},
        { prop: "operator", label: "操作  ",minWidth: 120,slotName: "operator"}
      ],
      // 操作列样式
      operatorConfig: {
        fixed: "right", // 固定列表右边（left则固定在左边）
        width: 200,
        label: "操作"
      }
    },
    loading:false,
    title: "发货验收详情信息",
    dialogSelectEnt:false,

    coseData:[],
    defaultSelectVal:[],
    ids:[],
    uploadValue:null

  })

  const fileListInstall = ref<UploadUserFile[]>([

  ])

  const fileListData = ref<UploadUserFile[]>([

  ])



  //表单配置
  const opts = ref({
    Code: {
      label: "条款类型编码",
      comp: "el-input"
    },
    Name: {
      label: "条款类型内容",
      comp: "el-input"
    }

  })

  //选择项
  const cusoptions = ref([])
  //是否签收
  const IsQS = ref(true)
  // 最终参数获取
  const getQueryData = computed(() => {
    const { Code, Name } = toRefs(
        state.queryData
    )
    return {
      Code: Code.value??'',
      Name: Name.value??''
    }
  })

  // 点击查询按钮
  const conditionEnter = (data: any) => {

    state.queryData = data

    getData()
  }

  //页面加载查询后端数据
  onMounted(() => {
    getData()
    initRoleList()
  })

  // 获取数据
  const getData = async () => {
    state.loading = true


    let data=await getTKType(getQueryData.value);

    if (data.Code==='OK'){

      state.table.data = data.Data
    }
    state.loading = false
  }


  //打开新增窗口
  async function addHandle() {


    let {Code}= await SaveTKType(state.table.data)
    if (Code==='OK'){
      ElMessage({
        message: '保存成功',
        type: 'success'
      })

      await getData()

    }

  }

  const clear = () => {

    selectTable.value.clear()
  }


  // 添加数据条数
  const num = ref(1)
  const singleEdit: any = ref(null)
  // 添加数据
  const add = () => {
    if (num.value > 0) {
      for (let i = 0; i < num.value; i++) {
        state.table.data.push({Id:null,Code:'',Name:''})
      }
    }
  }
  // 重置表单
  const reset = () => {

    state.coseData= []
    state.defaultSelectVal=[]

    singleEdit.value.resetFields()
  }

  //下拉表格选择数据
  const selectionChange = (e) => {
    state.coseData = e

  }

  //下拉表格选择数据
  const selecUpdateChange = (e) => {
    state.ids = e.map(item=>item.Id)

  }


  //选择标的
  const addToTable = () => {

    if (state.coseData.length<=0){
      ElMessage({
        message: '请选择标的',
        type: 'warning'
      })
      return
    }


    state.coseData.forEach(item=>{

      //相同数据不能添加
      if (state.clumTable.data.find(item1=>item1.Id===item.Id || item1.ConSubId===item.Id)){
        ElMessage({
          message: item.CinvName+'已存在，请勿重复添加',
          type: 'warning'
        })
        return
      }
      let Qty ={
        ...item,
        InvName:item.CinvName,
        InvStd:item.CinvAdd,
        InvCode:item.CinvCode,
        // Qty:item.Quantity,
        ConSubId: item.Id
      }
      state.clumTable.data.push(Qty)
    })
  }




  //校验表单需要定义ref
  let formRef =ref({})
  // 提交表单
  function submitForm() {
    //校验提交表单
    formRef.value.validate(async (vaild) => {
      if (vaild){
        if (state.clumTable.data.length<=0){
          return ElMessage({
            message: '请选择标的',
            type: 'warning'
          })
          return
        }

        let data={
          Main: {
            ...state.formData,
          },
          SubList:state.clumTable.data,
          FileList:state.FileList,
        }

       let {Code}= await SaveFHYS(data)
        if (Code==='OK'){
          ElMessage({
            message: '保存成功',
            type: 'success'
          })
          closeDialog()
          await getData()

        }

      }
    })


  }


  //删除表单
   function deleteHandles(row) {

    const ids = row.Id ? [row.Id] : state.ids;


    ElMessageBox.confirm(
        '请仔细核对数据，删除后无法恢复！',
        '审核提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          DelTKType({Ids:ids})
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          setTimeout(() => {
            getData()
            // 这里执行下一步操作
          }, 1000); // 等待3秒

        })
        .catch(() => {

        })
  }

  const initRoleList = async () => {
    let res = await userRole({ VT_ID: '条款类型管理' })
    state.roleList = res.items

  }

  </script>

  <style lang="scss" scoped>
  .single_edit_demo {
    .add_data {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 10px;
    }
  }
  </style>
